from simpy import Environment, Resource

from x_pc.core import Device, DeviceCost, System
from x_pc.model.model import Task


class GTPJ(Device, DeviceCost):
    """
    306 GTP拣选工作台
    GTP拣(GTPJ)
    """
    TIME_COST = 20
    # 资源
    resource: Resource = None

    def __init__(self, env: Environment, name: str):
        super().__init__(env, name)
        self.resource = Resource(env)

    def cost(self, *args, **kwargs) -> float:
        return self.TIME_COST


class GTPJSystem(System):
    """
    多穿GTP拣选台 系统
    """
    GTPJ_NUMS = 2
    # GTPJ列表
    gtpj_list: list[GTPJ] = []

    def __init__(self, env: Environment, name: str, code: str = None):
        super().__init__(env, name, code)
        self.__init_gtpj_list()

    def __init_gtpj_list(self):
        """
        初始化GTP列表
        :param env:
        :return:
        """
        self.gtpj_list = [GTPJ(self.env, f'GTP拣-{_ + 1}') for _ in range(self.GTPJ_NUMS)]

    def run_task(self, task: Task):
        if not self.gtpj_list:
            while self.running:
                yield self.env.timeout(1)
                if self.gtpj_list:
                    break
        #
        gtpj = self.gtpj_list.pop(0)
        with gtpj.resource.request() as req:
            yield req
            process = task.process
            #
            process.begin_ts = self.env.now
            #
            yield self.env.timeout(gtpj.cost())
            #
            process.end_ts = self.env.now
            process.device_code = gtpj.name
            # TODO: 根据任务的类型 分发至不同的目的地
            process.end_pos = None
        self.gtpj_list.append(gtpj)
